using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Winter.BackEnd.Models.Domain;
using System.Web.UI;
using System.Web.Mvc.Html;
using Winter.BackEnd.Models.Utils;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.Security;
using System.Xml;
using Winter.BackEnd.Models.DataTypes;

namespace Winter.BackEnd.Controllers
{
    [Authorize]
    public class GroupController : ApplicationController
    {

        #region ActionMethods
        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "student")]
        public ActionResult Schedule()
        {

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "student")]
        public ActionResult Index()
        {
            ViewData["Students"] = (from student in Repository.CurrentUser.Person.Student.Group.Students
                                    select new StudentDTO()
                                    {
                                        FullName = student.Person.FullName,
                                        ID = student.PersonID.ToString(),
                                        Image = student.Person.Image,
                                        UserName = student.Person.UserName,
                                        IsFriend = student.IsFriend,
                                        IsClassMonitor = student.Person.IsClassMonitor.HasValue ? student.Person.IsClassMonitor.Value : false
                                    }).ToArray();
            Person classMonitor = Repository.CurrentUser.Person.Student.Group.Students.
                SingleOrDefault(s => s.Person.IsClassMonitor.HasValue && s.Person.IsClassMonitor.Value).Person;

            ViewData["ClassMonitor"] = classMonitor.FullName;
            ViewData["ClassMonitorUserName"] = classMonitor.UserName;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "student"), ObjectFilter(Param = "eventDTO", RootType = typeof(EventDTO))]
        public JsonResult SaveEvent(EventDTO eventDTO)
        {
            var result = new JsonResult();

            //Event targetEvent = (Event)eventDTO;

            //targetEvent.PersonID = Repository.CurrentUser.Person.ID;

            //targetEvent.EventTypeID = 1;

            //if (Repository.CurrentUser.Person.Student.Group.GroupSchedules.Count != 0)
            //{
            //    targetEvent.ScheduleID = Repository.CurrentUser.Person.Student.Group.GroupSchedules.First().Schedule.ID;
            //}
            //else
            //{
            //    Repository.CurrentUser.Person.Student.Group.GroupSchedules.Add(new GroupSchedule()
            //    {
            //        Schedule = new Schedule() { Year = DateTime.Now }
            //    });
            //    targetEvent.ScheduleID = Repository.CurrentUser.Person.Student.Group.GroupSchedules.First().Schedule.ID;
            //}

            //Repository.CurrentDataContext.Events.InsertOnSubmit(targetEvent);

            //Repository.CurrentDataContext.SubmitChanges();

            #region old
            //var startDate = DateTime.ParseExact(string.Format("{0} {1}", start_date, start_time), "yyyy.MM.dd HH.mm.ss", null);
            //var endDate = DateTime.ParseExact(string.Format("{0} {1}", end_date, end_time), "yyyy.MM.dd HH.mm.ss", null);

            //try
            //{
            //    Repository.CurrentDataContext.Events.InsertOnSubmit(new Event()
            //    {
            //        event_pid = id,
            //        Description = text,
            //        event_length = event_legth,
            //        EventStartTime = startDate,
            //        EventEndTime = endDate,
            //        rec_type = rec_type != "null" ? rec_type : null,
            //        PersonID = 1,
            //        LetureRoom = "2",
            //        EventTypeID = 1,
            //        ScheduleID = Repository.CurrentUser.Person.Student.Group.GroupSchedules.First().Schedule.ID
            //    });

            //    Repository.CurrentDataContext.SubmitChanges();
            //}
            //catch (Exception ex)
            //{
            //    result.Data = new { errorMessage = ex.Message };
            //}
            #endregion

            return result;
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "student")]
        public JsonResult GetXMLSchedule()
        {
            JsonResult result = new JsonResult();

            int groupID = Repository.CurrentUser.Person.Student.GroupID;

            var events = Repository.GetEventsFroGroup(groupID);
            List<EventDTO> eventsJSON = new List<EventDTO>(); ;

            foreach (var scheduleEvent in events)
            {
                eventsJSON.Add(new EventDTO()
                {
                    end_date = scheduleEvent.EventEndTime.ToString("yyyy.MM.d HH.mm.ss"),
                    start_date = scheduleEvent.EventStartTime.ToString("yyyy.MM.d HH.mm.ss"),
                    custom_data = scheduleEvent.Description,
                    text = scheduleEvent.Description,
                    rec_type = scheduleEvent.rec_type,
                    event_length = scheduleEvent.event_length.HasValue ? scheduleEvent.event_length.ToString() : null
                });
            }

            result.Data = eventsJSON.ToArray();

            #region XML
            //using (XmlWriter xmlWriter = XmlTextWriter.Create(str))
            //{
            //    xmlWriter.WriteStartElement("data");
            //    {
            //        var events = Repository.GetEventsFroGroup(groupID);
            //        if (events != null)
            //        {
            //            foreach (var scheduleEvent in events)
            //            {
            //                xmlWriter.WriteStartElement("event");
            //                xmlWriter.WriteStartAttribute("id");
            //                xmlWriter.WriteValue(scheduleEvent.ID);
            //                xmlWriter.WriteEndAttribute();
            //                {
            //                    xmlWriter.WriteStartElement("id");
            //                    xmlWriter.WriteValue(scheduleEvent.event_pid != null ? scheduleEvent.event_pid : "");
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("start_date");
            //                    xmlWriter.WriteValue(scheduleEvent.EventStartTime.ToString("MM-dd-yyyy HH:mm:ss"));
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("end_date");
            //                    xmlWriter.WriteValue(scheduleEvent.EventEndTime.ToString("MM-dd-yyyy HH:mm:ss"));
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("text");
            //                    xmlWriter.WriteValue(scheduleEvent.Subject != null ? scheduleEvent.Subject.Name : scheduleEvent.Description);
            //                    xmlWriter.WriteEndElement();
            //                    xmlWriter.WriteStartElement("details");
            //                    xmlWriter.WriteValue(scheduleEvent.Description);
            //                    xmlWriter.WriteEndElement();
            //                    if (scheduleEvent.event_length.HasValue)
            //                    {
            //                        xmlWriter.WriteStartElement("event_length");
            //                        xmlWriter.WriteValue(scheduleEvent.event_length);
            //                        xmlWriter.WriteEndElement();
            //                    }
            //                    if (!string.IsNullOrEmpty(scheduleEvent.rec_type))
            //                    {
            //                        xmlWriter.WriteStartElement("rec_type");
            //                        xmlWriter.WriteValue(scheduleEvent.rec_type);
            //                        xmlWriter.WriteEndElement();
            //                    }
            //                }
            //                xmlWriter.WriteEndElement();
            //            }
            //        }
            //    }
            //    xmlWriter.WriteEndElement();
            //    xmlWriter.Close();
            //}
            #endregion

            return result;
        }

        public JsonResult GetDataFroCreatingSchedule()
        {
            var result = new JsonResult();
            result.Data = new
            {
                Subjects = from subject in Repository.CurrentDataContext.Subjects
                           select new { Name = subject.Name, ID = subject.ID },
                Buildings = from building in Repository.CurrentDataContext.Builgings
                            select new { Name = building.BuildingName, ID = building.ID },
                Teachers = from teacher in Repository.CurrentDataContext.Teachers
                           select new { Name = teacher.FullName, ID = teacher.ID }

            };
            return result;
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public ActionResult Details()
        {

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "admin")]
        public ActionResult Create()
        {

            ViewData["Groups"] = Repository.GetAllGroupForDropDown();
            ViewData["Days"] = Repository.GetAllDayOfWeekForDropDown();
            ViewData["Subjects"] = Repository.GetAllSubjectsForDropDown();
            ViewData["Teachers"] = Repository.GetAllTeachersForDropDown();

            return View();
        }

        #endregion

        #region HelperMethods

        private string FormatTime(TimeSpan time)
        {
            return string.Format("{0}:{1:D2}", time.Hours, time.Minutes);
        }

        #endregion

    }
}
